package com.pospi.pospihold.ui.static_ui;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.lany.sp.SPHelper;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.PayWayStaticAdapter;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dto.OrderBeen;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.PayBeen;
import com.pospi.pospihold.greendao.OrderBeenDao;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.DoubleSave;
import com.pospi.pospihold.util.GetData;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayWayStaticActivity extends BaseActivity {

    @Bind(R.id.chart)
    PieChart mChart;
    @Bind(R.id.lv_payment_chart)
    ListView lvPaymentChart;
    @Bind(R.id.sale_ranking_data)
    TextView saleRankingData;
    @Bind(R.id.sale_ranking_data_to)
    TextView saleRankingDataTo;
    @Bind(R.id.search)
    Button search;

    private String[] payments = new String[]{"现金", "银行卡", "支付宝", "微信", "积分", "其它"};
    private List<String> mParties = new ArrayList<>();
    private double totalMoney = 0;
    private double cashMoney = 0;
    private double cardMoney = 0;
    private double aliMoney = 0;
    private double wxMoney = 0;
    private double jifenMoney = 0;
    private double otherMoney = 0;
    private List<Double> doubles = new ArrayList<>();
    private PayWayStaticAdapter adapter;
    private List<OrderBeen> dtos;


    private int fromData;
    private int toData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_pay_way_static);
        setTitle("支付方式统计");
        ButterKnife.bind(this);


        saleRankingData.setText(GetData.getYYMMDDTime());
        fromData = GetData.getSearchTime();

        saleRankingDataTo.setText(GetData.getYYMMDDTime());
        toData = GetData.getSearchTime();
        addData();
        init();
    }

    private void addData() {
        dtos = App.getInstance().getDaoSession().getOrderBeenDao()
                .queryBuilder().where(OrderBeenDao.Properties.SaveTiem.ge(fromData),
                        OrderBeenDao.Properties.SaveTiem.le(toData),
                        OrderBeenDao.Properties.ShopNo.eq(SPHelper.getInstance().getString(Constant.SHOP_ID))).list();
        double saleMoney = 0;
        for (int i = 0; i < dtos.size(); i++) {
            saleMoney += Double.parseDouble(dtos.get(i).getAmount());
        }
        totalMoney = DoubleSave.doubleSaveTwo(saleMoney);
        /**
         * 把所有的支付方式相同的订单累加在一起
         */
        Log.i("size", dtos.size() + "");
        for (int i = 0; i < dtos.size(); i++) {
            OrderBeen good1 = dtos.get(i);
            String good_name1 = new Gson().fromJson(good1.getPayDetail(), PayBeen.class).getName();
            for (int j = dtos.size() - 1; j > i; j--) {
                OrderBeen good2 = dtos.get(j);
                String good_name2 = new Gson().fromJson(good2.getPayDetail(), PayBeen.class).getName();
                if (good_name1.equals(good_name2)) {
                    good1.setAmount(String.valueOf(Double.parseDouble(good1.getAmount()) + Double.parseDouble(good2.getAmount())));
                    dtos.remove(good2);
                }
            }
        }

        Collections.sort(dtos, new Comparator<OrderBeen>() {
            @Override
            public int compare(OrderBeen user1, OrderBeen user2) {
                Double id1 = Double.parseDouble(user1.getAmount());
                Double id2 = Double.parseDouble(user2.getAmount());
                //可以按User对象的其他属性排序，只要属性支持compareTo方法
                return id2.compareTo(id1);
            }
        });
        adapter = new PayWayStaticAdapter(getApplicationContext(), dtos);
        lvPaymentChart.setAdapter(adapter);


    }

    private void init() {
        mChart.setUsePercentValues(true);
        mChart.setDescription("");
        mChart.setExtraOffsets(5, 10, 5, 5);
        mChart.setDragDecelerationFrictionCoef(0.95f);
        mChart.setCenterText(generateCenterSpannableText());
        mChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);
        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(getResources().getColor(R.color.payWay_bg));
        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);//
        mChart.setHoleRadius(50f);//内圈半径
        mChart.setTransparentCircleRadius(51f);
        mChart.setDrawCenterText(true);

        mChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(true);
        mChart.setHighlightPerTapEnabled(true);
        //设置数据
        setData();
        mChart.animateY(1000, Easing.EasingOption.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);
        Legend l = mChart.getLegend();
        l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
        l.setEnabled(false);
    }


    /**
     * 设置中间标题的属性
     */
    private SpannableString generateCenterSpannableText() {
        SpannableString s = new SpannableString("日收入\n" + totalMoney);
        s.setSpan(new RelativeSizeSpan(2.5f), 0, s.length(), 0);//0, 3之间的字符的大小
        s.setSpan(new StyleSpan(Typeface.NORMAL), 0, 3, 0);
        s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 3, 0);
        s.setSpan(new RelativeSizeSpan(0.9f), 0, s.length(), 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), s.length() - String.valueOf(totalMoney).length(), s.length(), 0);//字体斜体
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - String.valueOf(totalMoney).length(), s.length(), 0);//字体蓝色
        return s;
    }

    private void setData() {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        // 此处设置每一块饼的比例，例：10就是10.0%
        for (int i = 0; i < dtos.size(); i++) {
            String name = new Gson().fromJson(dtos.get(i).getPayDetail(), PayBeen.class).getName();
            if (name.equals(Constant.PAYMENT_CASH_String)) {
                Log.i("data", dtos.get(i).getAmount()+"---"+name);
                cashMoney += Double.parseDouble(dtos.get(i).getAmount());
            } else if (name.equals(Constant.PAYMENT_BANK_CARD_String)) {
                cardMoney += Double.parseDouble(dtos.get(i).getAmount());
            } else if (name.equals(Constant.PAYMENT_ALIPAY_String)) {
                aliMoney += Double.parseDouble(dtos.get(i).getAmount());
            } else if (name.equals(Constant.PAYMENT_WEIXIN_String)) {
                wxMoney += Double.parseDouble(dtos.get(i).getAmount());
            } else if (name.equals(Constant.PAYMENT_INTEGAL_String)) {
                jifenMoney += Double.parseDouble(dtos.get(i).getAmount());
            } else if (name.equals(Constant.PAYMENT_OTHER_String)) {
                otherMoney += Double.parseDouble(dtos.get(i).getAmount());
            }
        }

        if (cashMoney > 0) {
            doubles.add(cashMoney);
            mParties.add(payments[0]);
        }
        if (cardMoney > 0) {
            doubles.add(cardMoney);
            mParties.add(payments[1]);
        }
        if (aliMoney > 0) {
            doubles.add(aliMoney);
            mParties.add(payments[2]);
        }
        if (wxMoney > 0) {
            doubles.add(wxMoney);
            mParties.add(payments[3]);
        }
        if (jifenMoney > 0) {
            doubles.add(jifenMoney);
            mParties.add(payments[4]);
        }
        if (otherMoney > 0) {
            doubles.add(otherMoney);
            mParties.add(payments[5]);
        }
        for (int i = 0; i < doubles.size(); i++) {
            yVals1.add(new Entry((float) (doubles.get(i) / totalMoney) * 100, 0));
        }
//        yVals1.add(new Entry((float) (cashMoney / totalMoney) * 100, 0));
//        yVals1.add(new Entry((float) (cardMoney / totalMoney) * 100, 1));
//        yVals1.add(new Entry((float) (aliMoney / totalMoney) * 100, 2));
//        yVals1.add(new Entry((float) (wxMoney / totalMoney) * 100, 3));
//        yVals1.add(new Entry((float) (jifenMoney / totalMoney) * 100, 4));
//        yVals1.add(new Entry((float) (otherMoney / totalMoney) * 100, 5));

//        ArrayList<String> xVals = new ArrayList<String>();
//        for (int i = 0; i < mParties.size(); i++)
//            xVals.add(mParties.get(i));

        PieDataSet dataSet = new PieDataSet(yVals1, "");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors
        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        // dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        PieData data = new PieData(mParties, dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
//        data.setValueTypeface(tf);
        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);
        mChart.invalidate();
    }

    @OnClick({R.id.sale_ranking_data, R.id.sale_ranking_data_to, R.id.search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sale_ranking_data:
                showPickerDialog(saleRankingData, SaleRankingActivity.FROM);
                break;
            case R.id.sale_ranking_data_to:
                showPickerDialog(saleRankingDataTo, SaleRankingActivity.TO);
                break;
            case R.id.search:
                if (toData >= fromData & toData <= GetData.getSearchTime()) {
                    addData();
                } else {
                    showToast("请选择正确的查询日期");
                }
                break;
        }
    }

    public void showPickerDialog(final TextView tv, final int num) {
        final Calendar c1 = Calendar.getInstance();
        DatePickerDialog dialog1 = new DatePickerDialog(PayWayStaticActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                c1.set(year, monthOfYear, dayOfMonth);
                tv.setText(DateFormat.format("yyyy-MM-dd", c1));
                switch (num) {
                    case SaleRankingActivity.FROM:
                        fromData = Integer.parseInt(DateFormat.format("yyyyMMdd", c1).toString());
                        break;
                    case SaleRankingActivity.TO:
                        toData = Integer.parseInt(DateFormat.format("yyyyMMdd", c1).toString());
                        break;
                }
            }
        }, c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH));
        dialog1.show();

    }

}
